<template>
  <header>
    <div class="search-return" @click="goBack">
      <span><</span>
    </div>
    <div class="search-main">
      <form action="" onsubmit="return false" @keyup.enter="goSearchList">
        <input type="search" placeholder="请输入要搜索的商品" v-model="searchVal" />
      </form>
    </div>
    <div class="search-btn" @click="goSearchList">搜索</div>
  </header>
</template>

<script setup>
import { ref, defineEmits, defineComponent, onMounted, onUnmounted, onBeforeUnmount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { emitter } from '@/common/utils/EventMitt'
const searchHeader = defineComponent({
  name: 'SearchHeader',
  // 组件的其他选项...
})

const emit = defineEmits(['goBack'])
const goBack = () => {
  if (route.name === 'SearchList') {
    router.push({ name: 'SearchIndex', query: { keyword: searchVal.value } })
  } else {
    emit('goBack')
  }
}

let router = useRouter()
let route = useRoute()

const searchVal = ref('')
let goSearchList = () => {
  if (!searchVal.value) return

  // 获取本地存储的搜索记录
  let searchList = localStorage.getItem('searchList') || '[]'
  let searchArray = JSON.parse(searchList)
  searchArray.unshift(searchVal.value)

  //ES6 Set去重
  const uniqueSet = new Set(searchArray)
  const newArray = Array.from(uniqueSet)
  localStorage.setItem('searchList', JSON.stringify(newArray))

  if (route.name === 'SearchIndex') {
    router.push({ name: 'SearchList', query: { keyword: searchVal.value } })
    // router.push('/list') //这种方法也可以
  } else {
    route.query.keyword = searchVal.value
  }
}

emitter.on('updata:Keyword', (keyword) => {
  searchVal.value = keyword
})

onUnmounted(() => {
  emitter.off('updata:Keyword', () => {})
})
</script>

<style>
header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 1.173333rem;
  /* background-color:#f5f5f5; */
  border-bottom: 1px solid #ccc;
}

.search-return,
.serach-btn {
  padding: 0 0.266666rem;
  color: #666;
}

.search-main {
  display: flex;
  align-items: center;
  width: 6.933333rem;
  height: 0.7rem;
}

.search-main form {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.search-main form input {
  width: 100%;
  height: 100%;
  padding: 0 0 0 0.25rem;
  border: 1px solid #ccc;
  /* 设置默认边框颜色 */
  transition: border-color 0.3s ease;
  /* 平滑过渡效果 */
  border-radius: 0.1875rem;
}

.search-main form input:focus {
  outline: none;
  /* 去掉默认的轮廓线 */
  border-color: #ff4466;
  /* 改变边框颜色 */
}

.search-btn {
  font-size: 0.46666rem;
}
</style>
